﻿using UnityEngine;
using System.Collections;

namespace Turret
{
    public class TurretBehaviour : Turret
    {
        public Transform muzzlePosition;
        public Transform turretBall;
        public Transform aim;

        private float nextMoveTime;

        protected override void Awake()
        {
            base.Awake();
        }

        protected override void Start()
        {
            base.Start();
            //Tags our turret will focus
            targetableTag[0] = "Ennemy_ground";
            targetableTag[1] = "Ennemy_air";
        }

        protected override void getMyStatTemplates()
        {
            statTemplates = statManager.BasicTurretStat;
        }

        protected override void Update()
        {
            base.Update();
            //If the target is set
            if (target)
            {
                //If the turret can move
                if (Time.time >= nextMoveTime)
                {
                    //Lerp to the aim gameObject's rotation
                    calculateAimPosition(target);
                    turretBall.rotation = Quaternion.Lerp(turretBall.rotation, aim.rotation, Time.deltaTime * turnSpeed);
                }
                //If the turret can fire
                if (Time.time >= nextFireTime)
                {
                    fire();
                }
            }
        }

        private void calculateAimPosition(Transform targetPos)
        {
            //Aim the target using the empty gameobjet
            aim.LookAt(targetPos);
        }

        private float ballRelativePosition()
        {
            return turretBall.transform.position.y + transform.position.y;
        }

        protected override void fire()
        {
            //Fire and update the move and fire timers
            nextFireTime = Time.time + reloadTime;
            nextMoveTime = Time.time + firePauseTime;
            if (target.GetComponent<EnnemyBehaviour>())
            {
                target.GetComponent<EnnemyBehaviour>().applyDamages(projectileDamage);
            }
            GameObject newProjectile = (GameObject) Instantiate(projectile, muzzlePosition.position, muzzlePosition.rotation);
            newProjectile.GetComponent<ProjectileBehaviour>().setStats(projectileRange, projectileSpeed, projectileDamage);
        }
    }
}
